<template>
  <div class="wrapper">
    <dx-header-bar title="修改密码"></dx-header-bar>
    <div class="content">
      <md-input-item title="用户名" :placeholder=userName
                     is-amount disabled></md-input-item>
      <md-input-item type="password" title="旧密码" v-model="oldPsw" placeholder="请输入旧密码">
      </md-input-item>
      <md-input-item type="password" title="新密码" v-model="psw" placeholder="请输入新密码">
      </md-input-item>
      <md-input-item type="password" title="确认新密码" v-model="newPsw" placeholder="请确认新密码">
      </md-input-item>
      <md-button type="primary" class="btn" @click="submit">提交</md-button>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import { DxHeaderBar } from '@/components';
import { InputItem, Button, Dialog, Toast } from 'mand-mobile';
import store from '@/store';
import { modifyPsw } from '@/api/login';
import { encryptBySHA1 } from '@/utils';
import { callNativeApi } from '@/utils/native';

export default {
  components: {
    DxHeaderBar,
    [InputItem.name]: InputItem,
    [Button.name]: Button
  },
  data() {
    return {
      userName: store.getters.userName,
      oldPsw: '',
      psw: '',
      newPsw: ''
    };
  },
  methods: {
    submit() {
      if (!this.oldPsw.trim()) {
        Dialog.alert({ content: '旧密码不能为空' });
        return;
      }
      if (!this.psw.trim()) {
        Dialog.alert({ content: '密码不能为空' });
        return;
      }
      const passwordCheckCallBack = this.passwordCheckHandler(this.psw);
      if (passwordCheckCallBack !== '') {
        Dialog.alert({ content: passwordCheckCallBack });
        return;
      }
      if (!this.newPsw.trim()) {
        Dialog.alert({ content: '确认新密码不能为空' });
        return;
      }
      if (this.psw !== this.newPsw) {
        Dialog.alert({ content: '两次输入的密码不相同' });
        return;
      }
      this.modifyPassword();
    },

    modifyPassword() {
      const params = {
        userPwd: encryptBySHA1(this.newPsw)
      };
      modifyPsw(params).then(result => {
        if (result.message === 'success') {
          Dialog.alert({ content: '修改成功' });
          const loginOut = callNativeApi('dxGoLogin');
          if (!loginOut) {
            this.$router.push({
              name: 'login'
            });
          }
        } else {
          Dialog.alert({ content: result.message });
        }
      }).catch(() => {
        Toast.succeed('失败!');
      });
    },
    passwordCheckHandler(pwd) {
      if (pwd === '') {
        return '密码不能为空！';
      }
      if (!this.passwordCheck1(pwd)) {
        return '密码请包含大小写字母、数字和特殊符号，至少8位，特殊符号包含：-!@#$%^&*()+?<>';
      }
      const userName = store.getters.userName;
      if (!this.passwordCheck2(pwd, userName)) {
        return '口令不能为账号名相关的正序、反序';
      }
      if (!this.isKeyBoardContinuousChar(pwd)) {
        return '口令不能含3位以上（含3位）键盘排序密码';
      }
      if (!this.lxStr(pwd)) {
        return '口令中不能出现3位以上（含3位）连续字母、数字';
      }
      //  不能相同字符（如111、aaa）连续3位或3位以上
      const re1 = /(\w)*(\w)\2{2}(\w)*/g;
      if (re1.test(pwd)) {
        return '口令中不能出现3位以上（含3位）重复字母、数字';
      }
      return '';
    },
    passwordCheck1(str) {
      const regex = new RegExp('(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,30}');
      return regex.test(str);
    },
    passwordCheck2(str1, str2) {
      return !(str1 === str2 || str1.split('').reverse().join('') === str2);
    },
    isKeyBoardContinuousChar(str) {
      const c1 = [
        ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+'],
        ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '{', '}', '|'],
        ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ':', '"'],
        ['z', 'x', 'c', 'v', 'b', 'n', 'm', '<', '>', '?']
      ];
      const c2 = [
        ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '='],
        ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\'],
        ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\''],
        ['z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/']
      ];
      const str1 = str.split('');
      //  获取坐标位置
      const y = [];
      const x = [];
      for (let c = 0; c < str1.length; c += 1) {
        y[c] = 0;//  当做~`键处理
        x[c] = -1;
        for (let i = 0; i < c1.length; i += 1) {
          for (let j = 0; j < c1[i].length; j += 1) {
            if (str1[c] === c1[i][j]) {
              y[c] = i;
              x[c] = j;
            }
          }
        }
        // eslint-disable-next-line
        if (x[c] !== -1) continue;
        for (let i = 0; i < c2.length; i += 1) {
          for (let j = 0; j < c2[i].length; j += 1) {
            if (str1[c] === c2[i][j]) {
              y[c] = i;
              x[c] = j;
            }
          }
        }
      }
      //  匹配坐标连线
      /* eslint-disable */
      for (let c = 1; c < str1.length - 1; c += 1) {
        if (y[c - 1] === y[c] && y[c] === y[c + 1]) {
          if ((x[c - 1] + 1 === x[c] && x[c] + 1 === x[c + 1]) ||
            (x[c + 1] + 1 === x[c] && x[c] + 1 === x[c - 1])) {
            return false;
          }
        } else if (x[c - 1] === x[c] && x[c] === x[c + 1]) {
          if ((y[c - 1] + 1 === y[c] && y[c] + 1 === y[c + 1]) ||
            (y[c + 1] + 1 === y[c] && y[c] + 1 === y[c - 1])) {
            return false;
          }
        }
      }
      return true;
    },
    lxStr(str) {
      const arr = str.split('');
      let flag = true;
      for (let i = 1; i < arr.length - 1; i += 1) {
        const firstIndex = arr[i - 1].charCodeAt(0);
        const secondIndex = arr[i].charCodeAt(0);
        const thirdIndex = arr[i + 1].charCodeAt(0);
        if ((thirdIndex - secondIndex === 1) && (secondIndex - firstIndex === 1)) {
          flag = false;
        }
      }
      return flag;
    }
  }
};
</script>

<style lang="stylus" scoped>
  .content
    padding : 0 20px
    background : #fff
    height : 100%
    width : 100%

  .btn
    margin : 40px 0
</style>
